/**
 * 工具函数集合
 */

// 导出所有工具
export * from './config.js'
export { default as wsManager } from './websocket.js'
export { default as logger } from './logger.js'

// 通用工具函数
export const utils = {
  /**
   * 防抖函数
   */
  debounce(func, wait, immediate = false) {
    let timeout
    return function executedFunction(...args) {
      const later = () => {
        timeout = null
        if (!immediate) func.apply(this, args)
      }
      const callNow = immediate && !timeout
      clearTimeout(timeout)
      timeout = setTimeout(later, wait)
      if (callNow) func.apply(this, args)
    }
  },

  /**
   * 节流函数
   */
  throttle(func, limit) {
    let lastFunc
    let lastRan
    return function(...args) {
      if (!lastRan) {
        func.apply(this, args)
        lastRan = Date.now()
      } else {
        clearTimeout(lastFunc)
        lastFunc = setTimeout(() => {
          if ((Date.now() - lastRan) >= limit) {
            func.apply(this, args)
            lastRan = Date.now()
          }
        }, limit - (Date.now() - lastRan))
      }
    }
  },

  /**
   * 深拷贝
   */
  deepClone(obj) {
    if (obj === null || typeof obj !== 'object') return obj
    if (obj instanceof Date) return new Date(obj.getTime())
    if (obj instanceof Array) return obj.map(item => this.deepClone(item))
    if (typeof obj === 'object') {
      const clonedObj = {}
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          clonedObj[key] = this.deepClone(obj[key])
        }
      }
      return clonedObj
    }
  },

  /**
   * 格式化文件大小
   */
  formatFileSize(bytes) {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return (bytes / Math.pow(k, i)).toFixed(1) + ' ' + sizes[i]
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return format
      .replace('YYYY', year)
      .replace('MM', month)
      .replace('DD', day)
      .replace('HH', hours)
      .replace('mm', minutes)
      .replace('ss', seconds)
  },

  /**
   * 生成随机字符串
   */
  randomString(length = 8) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  },

  /**
   * 检查是否为空值
   */
  isEmpty(value) {
    return value === null || 
           value === undefined || 
           value === '' || 
           (Array.isArray(value) && value.length === 0) ||
           (typeof value === 'object' && Object.keys(value).length === 0)
  },

  /**
   * 手机号校验
   */
  isValidPhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone)
  },

  /**
   * 身份证校验
   */
  isValidIdCard(idCard) {
    return /^\d{18}$/.test(idCard)
  },

  /**
   * 获取设备信息
   */
  getDeviceInfo() {
    try {
      return uni.getSystemInfoSync()
    } catch (error) {
      console.error('获取设备信息失败:', error)
      return {}
    }
  },

  /**
   * 获取当前页面路径
   */
  getCurrentPagePath() {
    try {
      const pages = getCurrentPages()
      if (pages.length > 0) {
        return pages[pages.length - 1].route
      }
    } catch (error) {
      console.error('获取当前页面失败:', error)
    }
    return ''
  },

  /**
   * 安全的 JSON 解析
   */
  safeJsonParse(str, defaultValue = null) {
    try {
      return JSON.parse(str)
    } catch (error) {
      return defaultValue
    }
  },

  /**
   * 延迟执行
   */
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }
}